package com.aliyunpdf.algorithmic_thinking.sort;

import java.util.Arrays;

/**
 * @author: jsh
 * @create: 2023/4/26 22:22
 * @Description:      数组变换
 * @FileName: ArrayTransformation
 * @History:
 * @自定义内容：
 */
public class ArrayTransformation {
    public static void main(String[] args) {

        int[] arr = {3,5,7,1,9};
        System.out.println(arrayTransformation(arr, 2));
    }

    public static int arrayTransformation(int[] arr, int d){
        int rem = arr[0] % d;
        for (int i = 0; i < arr.length; i++)
            if (rem != arr[i] % d)return -1;
        //升序排序
        Arrays.sort(arr);
        int res = Integer.MAX_VALUE;
        int l = 0, r = Arrays.stream(arr).sum() - arr[0];
        for (int i = 1; i < arr.length-1; i++) {
            l += arr[i-1];
            r -= arr[i];
            int a = (i * arr[i] - l) / d;
            int b =(r - (arr.length - i -1) * arr[i]) / d;
            res = Math.min(res, (i * arr[i] - l) / d + (r - (arr.length - i -1) * arr[i]) / d);
        }


        return res;
    }
}
